package com.zxr.demo.service.impl;
import com.zxr.demo.commom.bo.ChatMessage;
import com.zxr.demo.service.ChatService;
import com.zxr.demo.utils.JwtUtil;
import org.redisson.api.RList;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private QiniuAiService qiniuAiService;

    // AI回复处理（实际项目中可集成OpenAI等API）
    private String getAiResponse(String content) {
        // 简单示例：根据关键词回复
        if (content.contains("你好") || content.contains("hello")) {
            return "你好！有什么我可以帮助你的吗？";
        } else if (content.contains("再见")) {
            return "再见！欢迎下次再来~";
        } else {
            return "感谢你的消息：" + content + "，这是我的回复。";
        }
    }

    @Override
    public ChatMessage sendMessage(String token, String content) {
        try {
            // 1. 解析token获取用户名
            String actualToken = token.substring(7);
            String username = JwtUtil.getUsernameFromToken(actualToken);

            // 2. 创建用户消息
            ChatMessage userMessage = new ChatMessage();
            userMessage.setId(UUID.randomUUID().toString());
            userMessage.setUserId(username);
            userMessage.setUserName(username);
            userMessage.setContent(content);
            userMessage.setSendTime(LocalDateTime.now());
            userMessage.setSessionId("session_" + username);
            userMessage.setMessageType(1);

            // 3. 存储用户消息到Redis
            RList<ChatMessage> chatList = redissonClient.getList("chat_history:" + username);
            chatList.add(userMessage);

            // 4. 调用七牛云AI获取回复（使用历史消息）
            String aiResponse = qiniuAiService.getAiResponse(chatList);  // 修改这里

            // 5. 生成AI回复消息
            ChatMessage aiMessage = new ChatMessage();
            aiMessage.setId(UUID.randomUUID().toString());
            aiMessage.setUserId("AI");
            aiMessage.setUserName("智能助手");
            aiMessage.setContent(aiResponse);
            aiMessage.setSendTime(LocalDateTime.now());
            aiMessage.setSessionId("session_" + username);
            aiMessage.setMessageType(2);

            // 6. 存储AI回复
            chatList.add(aiMessage);
            chatList.expire(7, TimeUnit.DAYS);

            return aiMessage;
        } catch (Exception e) {
            throw new RuntimeException("发送消息失败", e);
        }
    }

    @Override
    public List<ChatMessage> getHistoryMessages(String token, Integer page, Integer size) {
        try {
            String actualToken = token.substring(7);
            String username = JwtUtil.getUsernameFromToken(actualToken);

            RList<ChatMessage> chatList = redissonClient.getList("chat_history:" + username);

            // 分页处理
            page = page == null ? 1 : page;
            size = size == null ? 20 : size;
            int start = (page - 1) * size;
            int end = Math.min(start + size, chatList.size());

            return chatList.subList(start, end);
        } catch (Exception e) {
            throw new RuntimeException("获取历史消息失败", e);
        }
    }

    @Override
    public Boolean clearHistory(String token) {
        try {
            String actualToken = token.substring(7);
            String username = JwtUtil.getUsernameFromToken(actualToken);

            RList<ChatMessage> chatList = redissonClient.getList("chat_history:" + username);
            chatList.clear();
            return true;
        } catch (Exception e) {
            throw new RuntimeException("清除历史消息失败", e);
        }
    }
}